from docx import Document
import os
from datetime import datetime

def split_text_by_sentence(text, min_len=60, max_len=120):
    segments = []
    start = 0
    buffer = ""  # 缓冲区，用于合并短句

    while start < len(text):
        # 寻找下一个句号（中英文）或回车符
        end_period1 = text.find("。", start)
        end_period2 = text.find(".", start)
        end_newline = text.find("\n", start)

        # 如果都没有，设为文本末尾
        end_period = min(
            end_period1 if end_period1 != -1 else len(text),
            end_period2 if end_period2 != -1 else len(text),
            end_newline if end_newline != -1 else len(text)
        )

        # 截取从 start 到下一个句号或回车符的片段
        segment = text[start:end_period + 1]  # 包含句号或回车符

        # 如果长度超过 max_len，尝试截断到上一个逗号（中英文）
        if len(segment) > max_len:
            # 在 start 到 start + max_len 范围内找最后一个逗号
            end_comma1 = text.rfind("，", start, start + max_len)
            end_comma2 = text.rfind(",", start, start + max_len)
            end_comma = max(end_comma1, end_comma2)

            if end_comma != -1 and end_comma > start:
                segment = text[start:end_comma + 1]
                start = end_comma + 1
            else:
                # 没有逗号，直接截断
                segment = text[start:start + max_len]
                start = start + max_len
        else:
            start = end_period + 1

        # 添加到缓冲区
        buffer += segment.strip() + " "

        # 如果缓冲区内容 >= min_len，输出并清空缓冲区
        if len(buffer.strip()) >= min_len:
            segments.append(buffer.strip())
            buffer = ""

    # 处理最后可能剩余的缓冲内容（如果不足 min_len，也输出）
    if buffer.strip():
        segments.append(buffer.strip())

    return segments

def word_to_txt(word_path, output_folder):
    # 获取当前时间戳，格式：YYYYMMDD_HHMMSS
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 读取 Word 文件
    try:
        doc = Document(word_path)
        full_text = "\n".join([para.text for para in doc.paragraphs])
    except Exception as e:
        print(f"读取 Word 文件失败：{e}")
        return

    # 拆分文本
    sentences = split_text_by_sentence(full_text)

    # 保存为多个 txt 文件，使用时间戳 + 三位序号命名
    file_index = 1
    for sentence in sentences:
        if not sentence.strip():  # 跳过空内容
            continue

        # 构造文件名：时间戳_三位序号.txt
        filename = f"{timestamp}_{file_index:03d}.txt"
        filepath = os.path.join(output_folder, filename)

        with open(filepath, "w", encoding="utf-8") as f:
            f.write(sentence.strip())
        
        file_index += 1

    print(f"成功拆分为 {file_index - 1} 个非空 txt 文件，保存在：{output_folder}")

# 示例调用
if __name__ == '__main__':
    word_file = r"d:\北京伊吕科技\应用场景\数据标注\文本标注\基因检测解码生命密码.docx"
    output_dir = r"d:/output_txt_files"

    word_to_txt(word_file, output_dir)